'''
Created on 27/04/2012

@author: Bruna, Bruno
'''

def calculate_mean(sum, count):
    return sum / float(count)
    
def calculate_variance(sum, sqr_sum, count):
    return (sqr_sum / (count - 1)) - ((sum*sum) / (count * (count - 1)))

def calculate_histogram(data, histogram_interval_count, histogram_upper_bound):
    histogram = Histogram(histogram_interval_count, histogram_upper_bound)
                
    for sample in data:
        histogram.add_sample(sample)
    
    return histogram
    
class Histogram:
    def __init__(self, histogram_interval_count, histogram_upper_bound):
        self.interval_count = histogram_interval_count
        self.upper_bound = histogram_upper_bound
        self.interval_size = self.upper_bound / float(self.interval_count)
        self.data = [0] * self.interval_count ** 3
        self.total_samples = 0

    def find_histogram_position(self, r, g, b):
        return (r * self.interval_count + g) + b * self.interval_count * self.interval_count
        
    def add_sample(self, (r,g,b)):
        r = int(r // self.interval_size)
        g = int(g // self.interval_size)
        b = int(b // self.interval_size)
        
        interval_position = self.find_histogram_position(r, g, b)
        self.data[interval_position] += 1
        self.total_samples += 1
        
    def probability(self, (r,g,b)):
        r = int(r // self.interval_size)
        g = int(g // self.interval_size)
        b = int(b // self.interval_size)
        
        interval_position = self.find_histogram_position(r, g, b)
        
        #print "P[rgb] =", self.data[interval_position]
        
        return self.data[interval_position] / float(self.total_samples)